<template>
  <div class="app-container">

    <CustomContent>
      <template v-slot:body>
        <div id="mmv-page" v-loading="loading">
          <MmvTitle title="车型信息"></MmvTitle>
          <el-form size="mini" label-width="130px" ref="form">

            <el-row :gutter="15">
              <el-col :span="12">

                <el-form-item label="所属车型" required v-if="planId">
                  <el-input :value="modelInfo" disabled style="width:100%" placeholder="品牌车系车型"></el-input>
                </el-form-item>
                <el-form-item label="选择车型" required v-else>
                  <el-input :value="modelInfo" readonly style="width:100%" placeholder="品牌车系车型" @click.native="showchexing=true">
                    <el-button slot="append" icon="el-icon-search" @click="showchexing=true"></el-button>
                  </el-input>

                  <el-dialog title="品牌车系车型" :visible.sync="showchexing" width="900px" append-to-body>
                    <el-row :gutter="10" class="mb10">
                      <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddModel" v-hasPermi="['order:orderBasic:add']">从车型库选择</el-button>
                      </el-col>
                    </el-row>
                    <el-table :data="configurationList">
                      <el-table-column label="品牌车系" prop="brandName"></el-table-column>
                      <el-table-column label="车型" prop="modelName"></el-table-column>
                      <el-table-column label="所属门店" prop="storeName"></el-table-column>
                      <el-table-column label="操作">
                        <template slot-scope="{row}">
                          <el-button type="text" @click="checkModel(row)">选择</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <pagination v-show="modeltotal>0" :total="modeltotal" :page.sync="configurationquery.pageNum" :limit.sync="configurationquery.pageSize" @pagination="getConfigurationList"/>
                  </el-dialog>

                  <el-dialog title="从车型库选择" :visible.sync="showAddModel" width="1000px" append-to-body @close="closeModelForm">
                    <el-form ref="modelForm" :model="modelForm"  :rules="rules" label-width="140px">
                      <el-row>
                        <el-col :span="24">
                          <div style="font-size: 20px">车型信息</div>
                          <el-form-item label="归属门店" prop="storeId" >
                            <el-select v-model="modelForm.storeId" placeholder="请选择归属门店" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in storeList" :key="item.storeId" :label="item.storeName" :value="item.storeId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="所属品牌" prop="carBrandId" >
                            <el-select v-model="modelForm.carBrandId" placeholder="请选择所属品牌" @change="getSeriesList" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in brandList" :key="item.brandId" :label="item.brandName" :value="item.brandId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="所属车系" prop="carSeriesId" >
                            <el-select v-model="modelForm.carSeriesId" placeholder="请选择所属车系" @change="getAllModelList" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in seriesList" :key="item.seriesId" :label="item.seriesName" :value="item.seriesId"></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="车型名称" prop="modelId" >
                            <el-select v-model="modelForm.modelId" placeholder="请选择所属车型" @change="checkNewModel" class="el-input-style" filterable remote>
                              <el-option v-for="(item, i) in allModelList" :key="item.id" :label="item.modelName" :value="item.id"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <div style="font-size: 20px">其他信息</div>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="车辆类型" prop="styleModel">
                              <el-select v-model="modelForm.styleModel" placeholder="请选择车辆类型" class="el-input-style">
                                <el-option v-for="dict in dict.type.style_model" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="变速箱" prop="speedChangingBox">
                              <el-select v-model="modelForm.speedChangingBox" placeholder="请选择变速箱" class="el-input-style">
                                <el-option v-for="dict in dict.type.speed_changing_box" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="燃油类型" prop="fuelType">
                              <el-select v-model="modelForm.fuelType" placeholder="请选择燃油类型" class="el-input-style">
                                <el-option v-for="dict in dict.type.fuel_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                        <el-col :span="12">
                          <div class="grid-content bg-purple">
                            <el-form-item label="排量" prop="displacement">
                              <el-select v-model="modelForm.displacement" placeholder="请选择排量" class="el-input-style">
                                <el-option v-for="dict in dict.type.displacement" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </el-form-item>
                          </div>
                        </el-col>
                      </el-row>
                      <el-row :gutter="20">
                        <el-col :span="12">
                          <el-form-item label="座位数" prop="seating">
                            <div class="grid-content bg-purple">
                              <el-select v-model="modelForm.seating" placeholder="请选择座位" class="el-input-style">
                                <el-option v-for="dict in dict.type.seat" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                              </el-select>
                            </div>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>

                    <div slot="footer" class="dialog-footer">
                      <el-button type="primary" :loading="addLoading" @click="addModelFormr">确 定</el-button>
                      <el-button @click="closeModelForm">取 消</el-button>
                    </div>
                  </el-dialog>

                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="车辆级别" prop="operatingClassification">
                  <el-select style="width:100%" filterable remote v-model="operatingClassification" clearable placeholder="请选择车辆级别">
                    <el-option v-for="(item,index) in rankList" :key="index" :value="item.rankId" :label="item.rankName">
                      {{ item.rankName }}
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>


            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="列表图片" prop="upcoverImage" class="is-required">
                  <MmvUploadImage @upImg="upcoverImageHandle" :autoCropWidth="235" :autoCropHeight="118" ref="coverImage" :size="2">
                    <el-button size="small" type="primary" icon="el-icon-upload" v-if="upcoverImage==null || upcoverImage==''">添加图片</el-button>
                    <div slot="tip" class="el-upload__tip">
                      支持JPG/JPEG/PNG，尺寸235*118px，不超过2M，仅限1张图片
                    </div>
                  </MmvUploadImage>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="详情图片" prop="detailsImage" class="is-required">
                  <MmvUploadImage @upImg="updetailsImage" ref="detailsImage" :more="true" :size="2" :autoCropWidth="375" :autoCropHeight="256">
                    <el-button size="small" type="primary" icon="el-icon-upload" v-if="detailsImage==null || detailsImage.length<10">添加图片</el-button>
                    <div slot="tip" class="el-upload__tip">
                      支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，可选10张图片
                    </div>
                  </MmvUploadImage>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="车型配置" prop="modelConfig">
                  <div>
                    <el-checkbox-group v-model="modelConfig">
                      <el-checkbox v-for="(dict,index) in dict.type.car_model_config_list" :key="index" :label="dict.value">{{ dict.label }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-form-item label="车型标签" prop="label">
                  <el-checkbox-group v-model="label">
                    <el-checkbox v-for="(dict,index) in dict.type.car_model_label" :key="index" :label="dict.value"> {{ dict.label }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="车辆押金" prop="deposit" class="is-required">
                  <el-input
                    v-model="deposit"
                    placeholder="请输入"
                    @keyup.native="deposit = oninput(deposit,2)"
                    @blur="deposit = oninput(deposit,2)"
                    clearable
                    style="width:200px">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="违章押金" prop="deposit">
                  {{ tenantConfig.illegalDeposit || 0}}
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <MmvTitle title="租金设置">

            <el-tooltip placement="right-start">
              <div slot="content" style="font-size: 14px">
                价格优先级: 特殊时段价格>节假日价格>日常租金
              </div>
              <el-button type="text">
                <i class="el-icon-warning-outline"></i>
              </el-button>
            </el-tooltip>

          </MmvTitle>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-table :data="holidayList" border max-height="420">
                <el-table-column label="价格名称" align="center" prop="dateName" min-width="120" show-overflow-tooltip></el-table-column>
                <el-table-column label="生效日期" align="center" prop="datepicker" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span v-if="scope.row.type=='weeksPrice'">周内（1-4）</span>
                    <span v-else-if="scope.row.type=='weekendPrice'">周末（5-7）</span>
                    <span v-else>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}至{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="单日价格（元）" align="center" prop="value" min-width="120" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <el-input
                      style="width:90%" placeholder="输入金额"
                      v-model="scope.row.value" @change="changePice(scope.row)"
                      @keyup.native="scope.row.value = oninput(scope.row.value,2)"
                      clearable>
                    </el-input>
                    元
                  </template>
                </el-table-column>
              </el-table>
            </el-col>


            <el-col :span="12">
              <el-calendar v-model="value" style="max-height: 520px">
                <template slot="dateCell"
                          slot-scope="{date, data}">
                  <div class="rili-wrap"
                       :class="{'is-selected':data.isSelected,aaaaaa:isEditaaaaaa(date)}"
                       style="padding:8px;height: 100%;">
                    <div class="rili-day">{{ data.day.split('-').slice(1).join('-') }}</div>
                    <div class="rili-price-wrap">
                      <div>￥{{ superMmv(date, rilijiage[date.getDay()]) }}</div>
                    </div>
                  </div>
                </template>
              </el-calendar>
            </el-col>
          </el-row>


          <MmvTitle title="保险价格"></MmvTitle>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-table :data="chargeInsureList" border @selection-change="handleSelectInsureChange" ref="insureTable" @row-click="clickInsureRow">
                <el-table-column type="selection" width="55" align="center"/>
                <el-table-column label="保险名称" align="center" prop="chargeItemsName" min-width="120" show-overflow-tooltip/>
                <el-table-column label="简介" align="center" prop="remark" min-width="120" show-overflow-tooltip/>
                <el-table-column label="价格" align="center" prop="unitPrice">
                  <template slot-scope="{ row }">
                    {{ row.unitPrice }} 元/天
                  </template>
                </el-table-column>
                <el-table-column label="收费天数上限" align="center" min-width="120" prop="upperLimitOfNumber">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfNumber && scope.row.upperLimitOfNumber >= 0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否可选" align="center" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row.isOptional | isOptional }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>

          <MmvTitle title="其他收费项"></MmvTitle>
          <el-row :gutter="15">
            <el-col :span="24">
              <el-table :data="chargeItemsList" border @selection-change="handleSelectItemsChange" ref="itemTable" @row-click="clickItemRow">
                <el-table-column type="selection" width="55" align="center"/>
                <el-table-column label="收费项名称" align="center" prop="chargeItemsName" min-width="120" show-overflow-tooltip/>
                <el-table-column label="收费项说明" align="center" prop="remark" min-width="120" show-overflow-tooltip/>
                <el-table-column label="价格" align="center" prop="unitPrice">
                  <template slot-scope="{ row }">
                    {{ row.unitPrice }} 元/
                    <dict-tag style="display: inline-block" :options="dict.type.charge_type" :value="row.chargeItemsType"/>
                  </template>
                </el-table-column>
                <el-table-column label="收费次数上限" align="center" min-width="120" prop="upperLimitOfNumber">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfNumber && scope.row.upperLimitOfNumber >= 0 ? scope.row.upperLimitOfNumber : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="收费金额上限" align="center" min-width="120" prop="upperLimitOfAmount">
                  <template slot-scope="scope">
                    <span>{{ scope.row.upperLimitOfAmount && scope.row.upperLimitOfAmount >= 0 ? scope.row.upperLimitOfAmount : '无上限' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否可选" align="center" min-width="80">
                  <template slot-scope="scope">
                    <span>{{ scope.row.isOptional | isOptional }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <template v-if="tenantConfig.nightServiceFee == 1">
            <MmvTitle title="夜间服务费"></MmvTitle>
            <el-row :gutter="15">
              <el-col :span="24">
                <el-descriptions direction="vertical" :column="4" border>
                  <el-descriptions-item label="时间" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeeStart }}至{{ tenantConfig.nightServiceFeeEnd }}</el-descriptions-item>
                  <el-descriptions-item label="价格（元/次）" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeePrice }}元/次</el-descriptions-item>
                  <el-descriptions-item label="说明" :span="2" :contentStyle="{'text-align': 'center'}" :labelStyle="{'text-align': 'center'}">{{ tenantConfig.nightServiceFeeRemark }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </template>

        </div>
      </template>
      <template v-slot:footer>
        <div class="footer">
          <el-button type="primary" @click.native="saveForm" :loading="addPlanLoading">保存</el-button>
          <el-button type="info" plain @click.native="close">取消</el-button>
        </div>
      </template>
    </CustomContent>
  </div>
</template>

<script>
import MmvTitle from '@/components/MmvUI/MmvTitle.vue'
import * as planApi from "@/api/plan/plan";
import map from 'lodash/map';
import forEach from 'lodash/forEach';
import MmvTable from './components/mmv-table.vue'

import moment from 'moment'
import MmvUploadImage from '../components/mmv-upload-image.vue'
import * as Utils from '@/utils'
import {
  listBasic
} from "@/api/car/car_basic";
import {tenantlist} from "@/api";
import CustomContent from "@/components/custom/content";
import {insertPlan, updatePlan2} from "@/api/plan/plan";
import cloneDeep from 'lodash/cloneDeep';
import {getCarBrandList, getCarModelList, getCarSeriesList, getStoreList ,insertModelBuss} from "@/api/car/model";
import {addInsurance, updateInsurance} from "@/api/maintenance/insurance";

export default {
  components: {
    MmvTitle,
    MmvTable,
    MmvUploadImage,
    CustomContent,
  },
  dicts: [
    'charge_type',
    'car_model_list_classification',
    'car_model_luxury_classification',
    'car_model_label',
    'operating_classification',
    'business_classification',
    'car_model_config_list', 'car_status',
    'style_model', 'speed_changing_box', 'displacement', 'fuel_type','seat'
  ],
  data() {
    return {
      planId:null,
      modelForm: {
        carBrandId: null,
        carSeriesId: null,
        modelId: null,
      },
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: '归属门店不能为空', trigger: 'blur' },
        ],
        carBrandId: [
          { required: true, message: '所属品牌不能为空', trigger: 'blur' },
        ],
        carSeriesId: [
          { required: true, message: '所属车系不能为空', trigger: 'blur' },
        ],
        modelId: [
          { required: true, message: '车型不能为空', trigger: 'blur' },
        ],
      },
      brandList: [],
      storeList: [],
      seriesList: [],
      allModelList: [],

      rankList: [],
      modelList: [],
      // 总条数
      total: 0,
      drawerFlag: false,
      addPlanLoading: false,
      direction: 'rtl',
      tenantId: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        carNo: null,
      },
      modeltotal: 0,
      modelloading: false,
      deposit: 0,
      weeksPrice: 0, // 周内价格
      weekendPrice: 0, // 周末价格
      //
      prevEdit: null,
      nowPrice: 0,
      nowEdit: null,
      loading: false,
      showchexing: false,
      showAddModel: false,
      addLoading: false,
      title: '',
      planName: '', // 车价名称
      //
      configurationId: '', // 品牌车系车型
      modelId: '',
      modelName: '',
      modelInfo: '',
      upcoverImage: '',
      detailsImage: [],
      modelConfig: [],
      //
      label: [],
      operatingClassification: "",
      //
      isSetMeal: 2, // 是否需要套餐车价
      // 是否显示弹出层
      open: false,
      openkehu: false, // 客户选择弹窗
      value: new Date(),
      list: [{
        mondayPrice: 0,
        tuesdayPrice: 0,
        wednesdayPrice: 0,
        thursdayPrice: 0,
        fridayPrice: 0,
        saturdayPrice: 0,
        sundayPrice: 0,
      }],
      checktable: [{}],
      checktableindex: 0,
      checklistteshutable: [{}],
      checklistteshutableindex: 0,
      radio: 0,
      chargeInsureList: [], // 保险项
      selectInsureIds: [], // 保险项ids
      chargeItemsList: [], // 收费项
      selectItemsIds: [], // 收费项ids
      configurationList: [], // 车型业务配置列表
      configurationquery: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
        configurationId: null
      },
      tenantConfig: {
        illegalDeposit: 0,
        pageSinightServiceFeeze: 2,
        nightServiceFeeStart: null,
        nightServiceFeeEnd: null,
        nightServiceFeePrice: null,
        nightServiceFeeRemark: null
      },
      // 节假日
      holidayList: [], // 节假日列表
    }
  },
  computed: {
    isEdit() {
      return !!this.form.planId;
    },
    rilijiage() {
      return {
        0: this.list[0].sundayPrice,
        1: this.list[0].mondayPrice,
        2: this.list[0].tuesdayPrice,
        3: this.list[0].wednesdayPrice,
        4: this.list[0].thursdayPrice,
        5: this.list[0].fridayPrice,
        6: this.list[0].saturdayPrice,
      }
    },
    // 节假日/特殊日期费用费用(无值时传空集合)
    planHolidayBillingList() {
      const arr = this.holidayList.filter(val => val.dateId && val.value >= 0)
      return map(arr, val => {
        return {
          holidayId: val.dateId, // 日期费用id(holidayType==1 必填)
          holidayType: val.dateType, // 费用类型（1节假日2特殊日期）
          holidayName: val.dateName, // 日期名称
          startTime: val.startTime, // 开始时间（年月日）
          endTime: val.endTime, // 结束时间（年月日）
          price: val.value || 0, // 费用
        }
      });
    },
    // 费用项
    chargeItemsBillingList() {
      let arr = [...this.selectItemsIds, ...this.selectInsureIds]
      return map(arr, val => {
        return {chargeItemsId: val}
      });
    },
    submitFormData() {
      return {
        planId: this.planId, // 车价ID
        configurationId: this.configurationId,
        operatingClassification: this.operatingClassification,
        modelConfig: String(this.modelConfig),
        label: String(this.label),
        deposit: this.deposit,
        weeksPrice: this.weeksPrice,
        weekendPrice: this.weekendPrice,
        upcoverImage: this.upcoverImage,
        detailsImage: this.detailsImage,
        planHolidayBillingList: this.planHolidayBillingList, // 节假日/特殊日期费用费用(无值时传空集合)
        chargeItemsBillingList: this.chargeItemsBillingList, // 费用项
      }
    },
  },
  watch: {
    weeksPrice(val) {
      this.list[0].mondayPrice = val;
      this.list[0].tuesdayPrice = val;
      this.list[0].wednesdayPrice = val;
      this.list[0].thursdayPrice = val;
    },
    weekendPrice(val) {
      this.list[0].fridayPrice = val;
      this.list[0].saturdayPrice = val;
      this.list[0].sundayPrice = val;
    },
  },
  async mounted() {
    this.loading = true;
    await this.getTenantConfig(); // 获取租户配置
    await this.getchargeItemsList(); // 获取收费项列表
    this.loading = false;
    this.planId = this.$route.query.planId;
    if (this.planId) {
      console.log('走修改流程');
      await this.getData();
    } else {
      await this.getholidayList(); // 获取节假日列表
    }
    await this.getConfigurationList(); // 获取车型业务配置列表
    this.getrankList();
  },
  methods: {

    clickItemRow(row) {
      this.$refs.itemTable.toggleRowSelection(row)
    },
    clickInsureRow(row) {
      this.$refs.insureTable.toggleRowSelection(row)
    },
    changePice(row) {
      if (isNaN(row.value)) {
        row.value = 0
      }
      if (row.type == 'weeksPrice') {
        this.weeksPrice = row.value
      } else if (row.type == 'weekendPrice') {
        this.weekendPrice = row.value
      } else {

      }
    },
    saveForm() {
      const form = this.submitForm()

      if (form.detailsImage?.length>0){
        form.detailsImage = form.detailsImage.map((item)=>{
          const containerStr=new RegExp("http");
          const isHttp = containerStr.test(item);
          if (isHttp){
            item = item.split('image-server/')[1]
          }
          return item
        })
      }
      console.log('url---------',form.detailsImage);
      this.form = cloneDeep(form)
      if (this.form.planId) {
        this.addPlanLoading = true
        updatePlan2(this.form)
          .then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.close()
          })
          .catch((err) => {
            this.addPlanLoading = false
          })
      } else {
        this.addPlanLoading = true
        insertPlan(this.form)
          .then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.close()
          })
          .catch((err) => {
            this.addPlanLoading = false
          })
      }
    },
    async getrankList() {

      if (this.planId) {
        tenantlist({tenantId: this.tenantId}).then(res => {
          this.rankList = res.data
        })
      } else {
        tenantlist().then(res => {
          this.rankList = res.data
        })
      }


    },
    handleSelectItemsChange(selection) {
      this.selectItemsIds = selection.map((item) => item.chargeItemsId)
    },
    handleSelectInsureChange(selection) {
      this.selectInsureIds = selection.map((item) => item.chargeItemsId)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getModelList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDrivingLicenseValidityDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    modelInventory() {
      this.drawerFlag = true;
      this.title = "车辆库存:" + this.modelInfo
      this.getModelList();
    },
    getModelList() {
      this.modelloading = true;
      this.queryParams.carModelId = this.modelId
      listBasic(this.queryParams).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.modelloading = false;
      });
    },
    handleClose(done) {
      done();
    },
    handleAddModel() {
      this.clearModelForm();
      getCarBrandList().then((response) => {
        this.brandList = response.data
      })

      getStoreList().then((response) => {
        this.storeList = response.data
      })
      this.showAddModel = true
    },
    checkModel(row) {
      this.showchexing = false;
      this.configurationId = row.configurationId;
      this.modelId = row.modelId;
      this.modelName = row.modelName;
      this.modelInfo = row.modelInfo;
      this.upcoverImage = row.upcoverImage;
      this.detailsImage = row.detailsImage;
      this.operatingClassification = "";
      this.$refs.coverImage.previewToUrl(Utils.getImgUrl(row.upcoverImage));
      this.$refs.detailsImage.previewToUrl(String(row.detailsImage.map(val => {
        return Utils.getImgUrl(val);
      })));
    },

    isShowEdit(data, date) {
      return data.isSelected && this.nowEdit == date.getTime();
      // return data.isSelected && this.nowEdit != date.getTime();
    },
    changeEdit(date) {
      this.nowPrice = this.superMmv(date, this.rilijiage[date.getDay()]);
      this.nowEdit = date.getTime();
    },
    okEdit(date) {
      this.nowEdit = null;
      this.prevEdit = date.getTime();
      // this.nowEdit = date.getTime();
      if (!this.nowPrice) return;
      this.addTeshuri(this.nowPrice, date, date);
    },
    //
    upcoverImageHandle(url) {
      console.log('----' + url)
      // 列表图片上传成功地址
      this.upcoverImage = url[0]
      // this.$refs['form'].validateField('upcoverImage')
    },
    updetailsImage(url) {
      // 详情封面上传成功地址
      // this.detailsImage = url.join(',')
      this.detailsImage = url
      // this.$refs['form'].validateField('detailsImage')
      console.log('上传成功的url=============',url);
    },
    /** 获取车型业务配置列表 */
    async getConfigurationList() {
      const result = await planApi.configurationList(this.configurationquery);
      this.configurationList = result.rows || [];
      this.modeltotal = result.total
    },
    /** 获取租户配置 */
    async getTenantConfig() {
      const result = await planApi.getTenantConfig();
      this.tenantConfig = result.data;
    },
    /** 获取节假日列表 */
    async getholidayList() {
      const result = await planApi.getSpecialDateByAdd({isEnable : 1});
      let arr = [
        {
          dateName: "周内价格",
          type: "weeksPrice",
          dateType: 0,
          value: this.weeksPrice,
        }, {
          dateName: "周末价格",
          type: "weekendPrice",
          dateType: 0,
          value: this.weekendPrice,
        }]
      this.holidayList = [...arr, ...result.data]
    },
    /** 获取收费项列表 */
    async getchargeItemsList() {
      const result = await planApi.chargeItemsList();

      for (let item of result.data) {
        item.checked = false
        if (item.projectType === 2) {
          this.chargeInsureList.push(item)
        } else {
          this.chargeItemsList.push(item)
        }
      }
    },

    /** 日历价格显示计算器 */
    superMmv(date, price) {
      // 计算出的价格
      let _price = price;

      function mmv(value) {
        // return value;
        const _date = new Date(value);
        return new Date(_date.getFullYear(), _date.getMonth(), _date.getDate()).getTime();
      }

      // 日历当前格子时间戳
      const time = mmv(date);
      // 遍历节假日数组
      require('lodash/forEach')(this.holidayList, val => {
        const start_time = mmv(val.startTime);
        const end_time = mmv(val.endTime);
        if (time <= end_time && time >= start_time && val.value != null) {
          _price = val.value;
        }
      });
      if (_price != '' && _price >= 0) {
        return _price
      } else {
        return this.rilijiage[date.getDay()]
      }
    },
    isEditaaaaaa(date) {
      function mmv(value) {
        // return value;
        const _date = new Date(value);
        return new Date(_date.getFullYear(), _date.getMonth(), _date.getDate()).getTime();
      }

      const time = mmv(date);
      // 遍历节假日数组
      const item = this.holidayList.find(val => {
        const start_time = mmv(val.startTime);
        const end_time = mmv(val.endTime);
        if (time <= end_time && time >= start_time) {
          return true
        }
      });
      return !!item
    },

    close() {
      // 关闭页面
      this.$router.go(-1)
      this.$store.dispatch('tagsView/delView', this.$route)
    },
    submitForm() {
      return this.submitFormData;
    },
    // 获取车系
    getSeriesList(carBrandId) {
      this.modelForm.carSeriesId = null
      this.modelForm.modelId = null
      this.seriesList = []
      this.allModelList = []
      getCarSeriesList(carBrandId).then((response) => {
        this.seriesList = response.data
      })
    },
    // 获取车型
    getAllModelList() {
      this.modelForm.modelId = null
      this.allModelList = []
      getCarModelList(this.modelForm.carSeriesId).then((response) => {
        this.allModelList = response.data
      })
    },
    checkNewModel(){
      let newModel=this.allModelList.filter(item=>{
        return item.id === this.modelForm.modelId
      })[0]
      this.modelForm.styleModel = newModel.styleModel
      this.modelForm.speedChangingBox = newModel.speedChangingBox
      this.modelForm.fuelType = newModel.fuelType
      this.modelForm.displacement = newModel.displacement
      this.modelForm.seating = newModel.seating
      this.modelForm.modelName = newModel.modelName
      this.modelForm.modelInfo = newModel.carBrandName+" "+ newModel.carSeriesName
    },
    closeModelForm(){
      this.showAddModel = false;
      this.clearModelForm();
      this.getConfigurationList();
    },
    clearModelForm(){
      this.modelForm={
        carBrandId: null,
        carSeriesId: null,
        modelId: null,
        styleModel: null,
        speedChangingBox: null,
        fuelType: null,
        displacement: null,
        seating: null
      }
    },
    addModelFormr(){

      this.$refs["modelForm"]?.validate(valid => {
        if (valid) {
          if(!this.modelForm.storeId){
            this.$modal.msgError('未选择门店')
          }else if(!this.modelForm.modelId){
            this.$modal.msgError('未选择车型')
          }else{
            this.addLoading = true;
            insertModelBuss(this.modelForm)
              .then((response) => {
                this.$modal.msgSuccess('添加成功')
                this.closeModelForm()
                this.addLoading = false
                this.checkModel(response.data)
              })
              .catch((err) => {
                this.addLoading = false
              })
          }
        }
      });
    },
    async getData() {
      this.loading = true;
      let holidayVoList = [];
      let itemsVoList = [];
      await planApi.getNewInfo(this.planId).then(response => {
        this.configurationId = response.data.configurationId;
        this.operatingClassification = response.data.operatingClassification;
        this.modelId = response.data.modelId;
        this.modelConfig = String(response.data.modelConfig).split(',');
        this.label = String(response.data.label).split(',');
        this.deposit = response.data.deposit;
        this.weeksPrice = response.data.weeksPrice;
        this.weekendPrice = response.data.weekendPrice;
        this.upcoverImage = response.data.upcoverImage;
        this.detailsImage = response.data.detailsImage;
        this.modelInfo = response.data.modelInfo;
        this.tenantId = response.data.tenantId;
        this.modelName = response.data.modelName
        holidayVoList = response.data.holidayVoList
        itemsVoList = response.data.itemsVoList
        //
        this.$refs.coverImage.previewToUrl(Utils.getImgUrl(response.data.upcoverImage));
        this.$refs.detailsImage.previewToUrl(String(response.data.detailsImage.map(val => {
          return Utils.getImgUrl(val);
        })));
        // 还原节假日/特殊日价格
        this.loading = false;
      });

      forEach(itemsVoList, val => {
        const item = this.chargeItemsList.find(_val => _val.chargeItemsId == val.chargeItemsId);
        if (item) {
          this.$refs.itemTable.toggleRowSelection(item, true)
        }
        const insure = this.chargeInsureList.find(_val => _val.chargeItemsId == val.chargeItemsId);
        if (insure) {
          this.$refs.insureTable.toggleRowSelection(insure, true)
        }
      });

      const result = await planApi.getSpecialDateByAdd({isEnable : 1});
      forEach(holidayVoList, val => {
        const item = result.data.find(_val => _val.dateId == val.holidayId);
        if (item) {
          item.value = val.price
        }
      });
      let arr = [
        {
          dateName: "周内价格",
          type: "weeksPrice",
          dateType: 0,
          value: this.weeksPrice,
        }, {
          dateName: "周末价格",
          type: "weekendPrice",
          dateType: 0,
          value: this.weekendPrice,
        }]
      this.holidayList = [...arr, ...result.data]
    },
    /** */
  },
}
</script>

<style>
#mmv-page .next {
  background: #f5f5f5;
}

#mmv-page .prev {
  background: #f5f5f5;
}

#mmv-page .el-calendar-day {
  padding: 0;
}

#mmv-page .next .rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #999;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;
}

.el-tooltip__popper {
  max-width: 500px;
}
</style>

<style lang="scss" scoped>
#mmv-page {

::v-deep .el-calendar-table .el-calendar-day {
  height: 60px;
}

}
.rili {
  width: 100%;
  height: 100%;
  font-size: 12px;
}

.rili-wrap {
  position: relative;
}

.el-icon-refresh-left {
  position: absolute;
  top: 8px;
  right: 8px;
}

.aaaaaa {
  background: rgb(253, 226, 226);
}

.rili-day {
  color: #999;
}

.rili-price-wrap {
  display: flex;
  align-items: center;
  padding: 5px 5px 0;
  color: #409eff;
  font-weight: bold;
  font-size: 16px;
  text-align: center;
  justify-content: center;
  white-space: nowrap;

}
</style>
